<?php

namespace app\common\model\mysql;

use think\Model;

class OrderProductNormal extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'or_order_product_normal';

    /**
     * 查询订单售普通商品数据列表
     * @param array $where
     * @param string $field
     * @return OrderProductWater[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNormalOrderProductNormal(array $where = [], string $field = "*"){
        $order = [
            "order_product_normal_id" =>"asc",
        ];
        $result = $this->where($where)->field($field)->order($order)->select();
        return $result->toArray();
    }

    /**
     * 查询订单售商品总量
     * @param array $where
     * @param string $field
     * @return float
     */
    public function getOrderProductNormalSum(array $where = [], string $field = "sellcount"){
        $result = $this->where($where)->sum($field);
        return $result;
    }

    /**
     * 计算总和
     * @param array $where 查询条件
     * @param string $expression 计算表达式，默认为 "SUM(a * b) as total"
     * @return int 计算结果
     */
    public function getOrderProductNormalSumTotal(array $where = [], string $expression = "SUM(a * b) as total")
    {
        // 使用 ThinkPHP 的查询构造器来构建自定义 SQL 查询
        $result = $this->where($where)
            ->fieldRaw($expression)
            ->find();

        // 返回计算结果
        return $result ? $result['total'] : 0;
    }

    /**
     * 根据where条件获取订单售商品数据
     * @param array $where
     * @param string $field
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderProductNormalFind(array $where = [], string $field = "*"){
        $result = $this->where($where)->field($field)->find();
        return $result ? $result->toArray() : [];
    }

    /**
     * 根据主键id更新数据表中的数据
     * @param $id
     * @param $data
     * @return bool
     */
    public function saveOrderProductNormalData($id,$data){
        $id = intval($id);
        if(empty($id) || empty($data) || !is_array($data)){
            return false;
        }
        $where = [
            "order_product_normal_id"=>$id,
        ];
        return $this->where($where)->save($data);
    }
}
